(function () {
	validateInit();
	//默认展开级别初始化
	$.ajax({
		url: "../basedata/query.action",
		type: "post",
		async: false,
		data: {"id" : "20171026000003"},
		success: function(data) {
			//console.log(data);
			$("tree-grid").attr('expand-level',data[0].level2Value);
		},
		error: function() {
			toastr.error("获取树级表格默认展开级别出错，请联系管理员");
		}
	});
	
	
	
	
	
	
    var app, deps;

    deps = ['treeGrid'];

    app = angular.module('treeGridTest', deps);

    app.controller('treeGridController', function ($scope, $timeout) {
        var tree;


        var myTreeData = getTreeData();

        $scope.tree_data = myTreeData;//赋值语句
        $scope.my_tree = tree = {};
        $scope.expanding_property = {
            field: "categoryName",
            displayName: "类别名",
            sortable: true,
            filterable: true,
            cellTemplate: "<i>{{row.branch[expandingProperty.field]}}</i>"
        };
        $scope.col_defs = [
            {
                field: "categoryDesc",
				displayName : "类别描述",
                sortable: true,
                sortingType: "string",
                filterable: true,
                cellTemplate: "<div class='td-cont-3'>{{row.branch.categoryDesc}}</div>"
            },{
                field: "categoryLevel",
				displayName : "级别",
                sortable: true,
                sortingType: "string",
                filterable: true
            },{
                field: "operate",
                displayName: "操作",
                //cellTemplate: "<span style='display:none'>{{row.branch.id}}</span><button class='btn btn-primary btn-xs' onclick='update(this)'>修改</button> <button class='btn btn-danger btn-xs' onclick='forbidden()'>禁用</button>"
                cellTemplate: "<div ng-controller=\"OperateController\"><button class=\"btn btn-primary btn-xs\" ng-click=\"update(row.branch)\">修改</button> <button ng-if=\"!isForbidden(row.branch)\" class=\"btn btn-danger btn-xs\" ng-click=\"forbidden(row.branch)\">删除</button><button ng-if=\"isForbidden(row.branch)\" class=\"btn btn-info btn-xs\" ng-click=\"removeForbidden(row.branch)\">启用</button></div>"
               }
        ];
        $scope.my_tree_handler = function (branch) {
            //console.log('you clicked on', branch)
        	
        }
    });
    app.controller('TableRowController', function($scope, $timeout) {
		$scope.tableRowDbClick = function(branch) {
			categoryDetail(branch);
		}
    });
    
    app.controller('OperateController', function($scope,$rootScope) {
    	$scope.isForbidden = function (branch) {
    		if (branch.categoryStatus == "0") {
    			return true;
    		}
    		return false;
    	}
    	$scope.update = function (branch) {
        	//console.log(branch);
        	update(branch);
        	//$rootScope.$$childHead.tree_data = getTreeData();//找这个方法找了n年，不熟悉的组件打印出来看一看
        }
    	
    	$scope.forbidden = function (branch) {
    		//console.log("禁用");
    		//console.log(branch);
    		
    		swal({
    	        title: "您确定要删除所选类别吗",
    	        text: "请确保该类别下无子类别，否则请先删除其子类别！",
    	        type: "warning",
    	        async: false,
    	        showCancelButton: true,
    	        confirmButtonColor: "#DD6B55",
    	        confirmButtonText: "删除",
    	        closeOnConfirm: false
    	    },function () {
    	    	var isExist = isExistSubMenu(branch.id, "1");
    	    	if (isExist) {
    	    		swal("删除失败", "该类别下存在子类别，请先删除其子类别", "error");
    	    		return;
    	    	} else if(isExist == "-1") {
    	    		swal("删除失败", "提交请求发生错误，请联系管理员", "error");
    	    		return;
    	    	}
    	    	$.ajax({
    	    		url: "../category/batchDelete.action",
    	    		type: "post",
    	    		data: {"categoryId":branch.id},
    	    		async: false,
    	    		success: function(data) {
    	    			if (data.success == "true") {
    	    				swal("删除成功", "您已经成功删除了所选类别。", "success");
    	    				result = "true";
    	    			} else {
    	    				swal("删除失败", "后台业务处理发生错误，请联系管理员", "error");
    	    			}
    	    		},
    	    		error: function() {
    	    			swal("操作失败", "提交到数据库发生错误，请联系管理员。", "error");
    	    		}
    	    	});
    	    	//console.log(result);
    	    	$rootScope.$$childHead.tree_data = getTreeData();//找这个方法找了n年，不熟悉的组件打印出来看一看
    	    	$rootScope.$apply();
    	    });
    	}
    		
    });
    app.controller('UpdateCategorySaveController', function($scope,$rootScope) {
    	$scope.updateCategorySave = function () {
    		console.log("save");
    		
    		updateCategorySave();
    		$rootScope.$$childHead.tree_data = getTreeData();//找这个方法找了n年，不熟悉的组件打印出来看一看
    	}
    });
    app.controller('addCategory', function($scope,$rootScope) {
    	$scope.addCategory = function () {
    		addCategory();
    	}
    });
    app.controller('addCategorySaveController', function($scope,$rootScope) {
    	$scope.saveCategory = function () {
    		var result = saveCategory();
    		if (result == "refresh") {
    			$rootScope.$$childHead.tree_data = getTreeData();//找这个方法找了n年，不熟悉的组件打印出来看一看
    		}
    	}
    });
    
}).call(this);

function isExistSubMenu(categoryId, status) {
	var result = true;
	$.ajax({
		url: "../category/isExistSubcategory.action",
		type: "post",
		data: {"parentCategoryId": categoryId, "categoryStatus": status},
		async: false,
		success: function(data) {
			//alert(data.success);
			if (data.success == "true") {
				result = true;
			}else{
				result = false;
			}
		},
		error: function() {
			result = -1;
		}
	});
	return result;
}

//父级类别是否选择了
var isBsSuggestSelected = false;
var isUpdateBsSuggestSelected = true;
//表单验证
function validateInit() {
	$.validator.addMethod("isBsSuggestSelected", function(value, element) { 
        return isBsSuggestSelected;       
	}, "必须选择给定的父级类别"); 
	$.validator.addMethod("isUpdateBsSuggestSelected", function(value, element) { 
		return isUpdateBsSuggestSelected;       
	}, "必须选择给定的父级类别"); 
	$("#addCategoryForm").validate({
			rules : {
				suggestParentCategoryId : {
					required : true,
					isBsSuggestSelected : true
				},
				categoryName : {
					required : true,
					remote : {
						url : "../category/categoryCheckRepect.action",
						type : "post",
						data : {
							"categoryName" : function() {
								return $("#addCategoryForm [name='categoryName']").val();
							}
						}
					}
				},
				categoryLevel: {
					required : true
				}
			},
			messages : {
				suggestParentTopicId : {
					required : "必选"
				},
				categoryName : {
					remote : "此类别名称已经存在"
				}
			},
			success : function(label, element) {// error是lavel标签，element是input标签
				labelReset(element);

				var myTipLabel = '<i class="glyphicon glyphicon-ok form-control-feedback my-tip-i"></i>';
				
				validCssApply(element, myTipLabel, 'has-success');
				
			},
			errorPlacement : function(label, element) {
				labelReset(element);

				var myTipLabel = '<i class="glyphicon glyphicon-remove form-control-feedback my-tip-i"></i>'
								+'<label class="control-label my-tip-label">'
								+	label.text()
								+'</label>';
				element.addClass("error");
				
				validCssApply(element, myTipLabel, 'has-error');
				 
			}
		});
	$("#updateCategoryForm").validate({
		rules : {
			categoryName : {
				required : true,
				remote : {
					url : "../category/updateCategoryCheckRepect.action",
					type : "post",
					data : {
						"categoryName" : function() {
							return $("#updateCategoryForm [name='categoryName']").val();
						},
						"categoryId":function() {
							return $("#updateCategoryForm [name='id']").val();
						}
					}
				}
			},
			categoryLevel: {
				required : true,
			}
		},
		messages : {
			categoryName : {
				remote : "此类别名称已经存在"
			}
		},
		success : function(label, element) {// error是lavel标签，element是input标签
			labelReset(element);

			var myTipLabel = '<i class="glyphicon glyphicon-ok form-control-feedback my-tip-i"></i>';
			element.parent().append(myTipLabel);
			element.parent().parent().addClass('has-success');
		},
		errorPlacement : function(label, element) {
			labelReset(element);

			var myTipLabel = '<i class="glyphicon glyphicon-remove form-control-feedback my-tip-i"></i>'
							+'<label class="control-label my-tip-label">'
							+	label.text()
							+'</label>';
			element.addClass("error");
			element.parent().append(myTipLabel);
			element.parent().parent().addClass('has-error');
		}
	});
}

//查询类别数据并树形化

function getTreeData() {
	var rawTreeData = '';
    $.ajax({
    	url: "../category/getAllEquipment.action",
    	type: "post",
    	async: false,
    	success: function(data) {
    		rawTreeData = data;
    	},
    	error: function() {
    		toastr.error("获取类别数据出错，请联系管理员");
    	}
    });
    var data = rawTreeData;
    var primaryIdName = 'id';
    var parentIdName = 'parentCategoryId';
    if (!data || data.length == 0 || !primaryIdName || !parentIdName)
        return [];

    var tree = [],
        rootIds = [],
        item = data[0],
        primaryKey = item[primaryIdName],
        treeObjs = {},
        parentId,
        parent,
        len = data.length,
        i = 0;

    while (i < len) {
        item = data[i++];
        primaryKey = item[primaryIdName];
        treeObjs[primaryKey] = item;
        parentId = item[parentIdName];

        if (parentId != -1) {
            parent = treeObjs[parentId];

            if (parent.children) {
                parent.children.push(item);
            } else {
                parent.children = [item];
            }
        } else {
            rootIds.push(primaryKey);
        }
    }

    for (var i = 0; i < rootIds.length; i++) {
        tree.push(treeObjs[rootIds[i]]);
    };
    return tree;
}

//类别详情
function categoryDetail(category) {
	var categoryDetailHtml = '<p style="text-align: center; color: #6294AD;"><b>基本信息</b></p>'
					+'<p>id：' + category.id + '</p>'
					+	'<p>类别名：' + category.categoryName + '</p>'
					+	'<p>类别描述：<pre style="white-space: pre-wrap !important;word-wrap: break-word !important;">' + category.categoryDesc + '</pre></p>'
					+	'<p>级别：' + category.categoryLevel + '</p>'
					
					+'<hr/><p style="text-align: center; color: #6294AD;"><b>其他信息</b></p>'
						
					+	'<p>创建人：' + getUserNameById(category.createUserId) + '</p>'
					+	'<p>创建时间：' + getDefaultTime(category.createTime) + '</p>'
				
	$("#categoryDetailShow").html(categoryDetailHtml);
	$("#categoryDetailModal").modal("show");
}
//新增类别
function addCategory() {//添加新类别
	formReset("#addCategoryForm");
	addCategoryFormInit();
	$("#addCategoryModal").modal("show");	
}
function addCategoryFormInit() {
	$.ajax({
		url: "../category/getAllEquipment.action",
		type: "post",
		success: function(data) {
			var array = [];
			array.splice(0, 0,{'id': '-1', 'word': '超顶级'});
			for(var i=0;i<data.length;i++){
			     var temp = {"id":data[i].id, 'word':data[i].categoryName};
			     array.push(temp);
			}
			
			$("#parentCategoryId").bsSuggest("destroy");
			
			var bsSuggestAreaHtml = '<div class="input-group">'
							      +     '<input type="text" placeholder="支持模糊搜索" class="form-control" id="parentCategoryId" name="suggestParentCategoryId" >'
							      +     '<input type="hidden" name="parentCategoryId" value="-1"/>'
							      +     '<div class="input-group-btn" id="suggestDiv">'
							      +         '<button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown">'
							      +             '<span class="caret"></span>'
							      +         '</button>'
							      +         '<ul class="dropdown-menu dropdown-menu-right my-treetable-hover" role="menu">'
							      +         '</ul>'
							      +     '</div>'
							      +  '</div>';
			$("#bsSuggestArea").html(bsSuggestAreaHtml);
			
			$("#parentCategoryId").bsSuggest({
				indexId: 0, 
				indexKey: 1, //data.value 的第几个数据，作为input输入框的显示内容
				data: {'value': array}
			}).on('onSetSelectValue', function (e, keyword) {  
				isBsSuggestSelected = true;
				$("#addCategoryForm [name='parentCategoryId']").val(keyword.id);
			}).on('onUnsetSelectValue', function (e) {  
				isBsSuggestSelected = false;
			});  
		},
		error: function() {
		}
	});
}
//新增保存
function saveCategory() {//添加新类别保存
	if (!$("#addCategoryForm").valid()) {
		return false;
	}
	var result = 'noRefush'
	var data = $("#addCategoryForm").serialize();
	
	$.ajax({
		url: "../category/saveCategory.action",
		type: "post",
		data: data,
		async: false,//将数据传出去
		success: function(data) {
			if (data.success == "true") {
				result = "refresh";
				toastr.success("保存成功");
			}
		},
		error: function() {
			toastr.error("提交到数据库发生错误，请联系管理员");
		}
	});
	$("#addCategoryModal").modal("hide");
	return result;
}

function update(data) {//修改类别
	formReset("#updateCategoryForm");
	$("#updateCategoryModal [name='categoryName']").val(data.categoryName);
	$("#updateCategoryModal [name='parentCategoryId']").val(data.parentCategoryId);
	$("#updateCategoryModal [name='categoryDesc']").text(data.categoryDesc);
	$("#updateCategoryModal [name='id']").val(data.id);
	$("#updateCategoryModal").modal("show");
}

function updateCategorySave() {//修改后保存
	if (!$("#updateCategoryForm").valid()) {
		return false;
	}
	var category = $("#updateCategoryForm").serialize();
	console.log(category);
	$.ajax({
		url: "../category/updateSave.action",
		type: "post",
		data: category,
		async: false,//将数据传出去
		success: function(data) {
			if (data.success == "true") {
				toastr.success("更新成功");
			}
		},
		error: function() {
			toastr.error("提交到数据库发生错误，请联系管理员");
		}
	});
	
	$("#updateCategoryModal").modal("hide");
}





function goToCategoryPage() {
	window.location.href = "../category/page.action";
}


//添加类别的类别下拉框

function suggest1(){//修改类别的类别下拉框
	$.ajax({
		url: "../category/getAllEquipment.action",
		type: "post",
		success: function(data) {
			console.log(data);
			var array = [];
			for(var i=0;i<data.length;i++){
			     var temp = {"categoryName":data[i].categoryName};
			     array.push(temp);
			}
			//console.log(array);
			    //添加设备的下拉框
				var testBsSuggest = $("#testNoBtn").bsSuggest({
				    data:array,
				    showBtn: false,
				    idField: "userId",
				    //keyField: "catgorName",
				    indexKey: 0,
				    effectiveFieldsAlias: {}, 
				    listHoverStyle: 'background: #18a689; color:#fff'
				}).on('onDataRequestSuccess', function (e, result) {
				    console.log('onDataRequestSuccess: ', result);
				}).on('onSetSelectValue', function (e, keyword) {
				    console.log('onSetSelectValue: ', keyword);
				}).on('onUnsetSelectValue', function (e) {
				    console.log("onUnsetSelectValue");
				});
				//修改设备的类别下拉框
				var testBsSuggest = $("#testNoBtn2").bsSuggest({
				    data:array,
				    showBtn: false,
				    idField: "userId",
				    //keyField: "catgorName",
				    indexKey: 0,
				    listHoverStyle: 'background: #18a689; color:#fff'
				}).on('onDataRequestSuccess', function (e, result) {
				    console.log('onDataRequestSuccess: ', result);
				}).on('onSetSelectValue', function (e, keyword) {
				    console.log('onSetSelectValue: ', keyword);
				}).on('onUnsetSelectValue', function (e) {
				    console.log("onUnsetSelectValue");
				});
		},
		error: function() {
		}
	});
}